package com.photography.interceptor;

import com.photography.annotation.RequireRole;
import com.photography.common.JwtTokenUtils;
import com.photography.exception.CustomException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;

/**
 * 角色权限拦截器
 * 用于拦截带有@RequireRole注解的请求，验证用户角色权限
 */
@Component
public class RoleInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(RoleInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取方法上的注解
        RequireRole requireRole = handlerMethod.getMethodAnnotation(RequireRole.class);
        if (requireRole == null) {
            // 获取类上的注解
            requireRole = handlerMethod.getBeanType().getAnnotation(RequireRole.class);
        }
        
        // 如果没有@RequireRole注解，直接通过
        if (requireRole == null) {
            return true;
        }

        // 获取当前用户角色
        String currentRole = JwtTokenUtils.getCurrentRole();
        if (currentRole == null) {
            throw new CustomException("未登录或登录已过期");
        }

        // 检查角色权限
        String[] requiredRoles = requireRole.value();
        if (!Arrays.asList(requiredRoles).contains(currentRole)) {
            log.warn("权限不足，当前角色：{}，需要的角色：{}", currentRole, Arrays.toString(requiredRoles));
            throw new CustomException("权限不足");
        }

        return true;
    }
} 